package com.my.mail2.service.impl.other;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.my.mail2.service.impl.AbstractEmailService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

/**
 * 抽象阿里邮箱基础服务
 */
@Data
@Slf4j
@Service
public class AbstractAliEmailService extends AbstractEmailService {

    private String accessKeyId;

    private String accessSecret;

    private String regionId;

    private String accountName;

    private String fromAlias;

    private IAcsClient iAcsClient;

    private IAcsClient getAcsClient() {
        if (this.iAcsClient == null) {
            synchronized (AbstractAliEmailService.class) {
                if (this.iAcsClient == null) {
                    // 如果是除杭州region外的其它region（如新加坡、澳洲Region），需要将下面的”cn-hangzhou”替换为”ap-southeast-1”、或”ap-southeast-2”。
                    IClientProfile profile = DefaultProfile.getProfile(this.regionId, this.accessKeyId, this.accessSecret);
                    this.iAcsClient = new DefaultAcsClient(profile);
                }
            }
        }
        return this.iAcsClient;
    }

    @Override
    public boolean sendEmail(String toAddress, String subject, String htmlBody, String textBody) {
        try {
            SingleSendMailRequest request = new SingleSendMailRequest();
            //在配置文件配置
            //request.setVersion("2017-06-22");// 如果是除杭州region外的其它region（如新加坡region）,必须指定为2017-06-22
            request.setAccountName(accountName);
            request.setFromAlias(fromAlias);
            request.setAddressType(1);
            request.setTagName("100");
            request.setReplyToAddress(true);
            request.setToAddress(toAddress);
            //可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
            //request.setToAddress("邮箱1,邮箱2");
            // 设置邮件内容
            request.setSubject(subject);
            request.setHtmlBody(htmlBody);
            request.setTextBody(textBody);
            //开启需要备案，0关闭，1开启
            //request.setClickTrace("0");
            //如果调用成功，正常返回httpResponse；如果调用失败则抛出异常，需要在异常中捕获错误异常码；错误异常码请参考对应的API文档;
            HttpResponse response = this.getAcsClient().doAction(request, true, 1);
            log.info("阿里推送 发送邮件结果：{}", JSON.toJSON(response));
            if (HttpStatus.SC_OK == response.getStatus()) {
                return true;
            }
        } catch (ClientException e) {
            // 捕获错误异常码
            log.error("阿里推送 发送邮件异常：ErrCode: {}  ErrMsg: {}", e.getErrCode(), e.getErrMsg());
        }
        return false;
    }
}
